import type { UserInfo } from '@/api/user'
import  { getUserInfoApi, getUserMenu } from '@/api/user'
import type { MenuData } from '@/layout/basic-layout/typing'
import { generateFlatRoutes, generateTreeRoutes } from '@/router/generate-route'
import { rootRoute } from '@/router/constant'

export const useUserStore = defineStore('user', () => {
  const routerData = shallowRef()
  const userInfo = shallowRef<UserInfo>()
  const menuData = shallowRef<MenuData>([])
  const token = useAuthorization()

  const getMenuRoutes = async () => {
    const { data } = await getUserMenu()
    console.log('menuData', data)
    return generateTreeRoutes(data ?? [])
  }

  const generateDynamicRoutes = async () => {
    const dynamicLoadWay =  getMenuRoutes;
    const { menuData: treeMenuData, routeData } = await dynamicLoadWay()

    menuData.value = treeMenuData
    console.log('treeMenuData', treeMenuData)
    routerData.value = {
      ...rootRoute,
      children: generateFlatRoutes(routeData),
    }
    console.log('routerData', routerData.value)
    return routerData.value
  }

  // 获取用户信息
  const getUserInfo = async () => {
    // 获取用户信息
    const { data } = await getUserInfoApi()
    userInfo.value = data
  }
  const logout = async () => {
    // 退出登录
    // 1. 清空用户信息
    try {
      //await logoutApi()
    }
    finally {
      token.value = null
      userInfo.value = undefined
      routerData.value = undefined
      menuData.value = []
    }
  }
  return {
    userInfo,
    getUserInfo,
    routerData,
    menuData,
    generateDynamicRoutes,
  }
})
